package com.reer.http;

import android.util.Log;
import com.reer.Const;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;


/**
 * HTTP连接工具。应 与GUI运行在不同线程下。
 */
public class HttpConnection {

    private boolean mAbort;// 是否主动关闭连接
    private HttpClient mClient;
    private HttpPost mPost;
   private static final int TIME_OUT_SEC=10;

    public void abort() {
        mAbort = true;
        Log.e(Const.TAG, "HttpConnection:abort request");
        if (mPost != null) {
            mPost.abort();
        }
        closeConnection();
    }

    /**
     * 主动关闭网络连接。
     */
    public void closeConnection() {
        if (mClient != null) {
            Log.i(Const.TAG, "HttpConnection:close connection");
            mClient.getConnectionManager().shutdown();
        }
    }

    /**
     * 发起POST请求，取得响应字符串。如果HTTP StatusCode不是200，则返回null。
     *
     * @param uri
     * @return
     * @throws NetworkingException
     * @throws NetworkingAbortException
     */
    String post(UriConstants uri, String data)
            throws NetworkingException, NetworkingAbortException {
        Log.d(Const.TAG, "HttpConnection:HTTP POST excuting");
        mAbort = false;
        mClient = new DefaultHttpClient();

        BufferedReader br = null;
        String resp = null;
        try {
            mPost = new HttpPost(uri.getUri());
            StringEntity myEntity = new StringEntity(data, "utf-8");
            mPost.setEntity(myEntity);
            HttpConnectionParams.setConnectionTimeout(mPost.getParams(), TIME_OUT_SEC * 1000);
            HttpResponse response = mClient.execute(mPost);

            String newLine = System.getProperty("line.separator");
            StringBuffer sb = new StringBuffer("");

            List<String> lines = IOUtils.readLines(response.getEntity().getContent(), "utf-8");
            for (String line : lines) {
                sb.append(line + newLine);
            }
            resp = sb.toString();
            Log.v(Const.TAG, "HttpConnection:response string:"+ resp);

            int statusCode = response.getStatusLine().getStatusCode();
            Log.d(Const.TAG,"HttpConnection:response status code:" + statusCode);

            if (statusCode != HttpStatus.SC_OK) {
                Log.e(Const.TAG,"HttpConnection:wrong response status code:"+ statusCode);
                Log.d(Const.TAG,"HttpConnection:HTTP POST response string:"+ sb.toString());
                resp = null;
            }

        } catch (IOException e) {
            Log.e(Const.TAG, "HttpConnection:is aborted?"+ mAbort);
            Log.e(Const.TAG,"HttpConnection:I/O exception:" + e.getStackTrace().toString());
            resp = null;
            if (!mAbort) {
                throw new NetworkingAbortException();
            } else {
                throw new NetworkingException(e);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if (mClient != null) {
                    mClient.getConnectionManager().shutdown();
                    Log.i(Const.TAG,"HttpConnection:connection closed");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d(Const.TAG, "HttpConnection:HTTP POST finished");
        return resp;
    }

}
